require 'rubygems'
require 'macaddr'
require 'uuidtools'
require 'digest/sha1'

include UUIDTools

class UsersController < ApplicationController
  before_filter :login_required,:except=>[:new,:check_login,:check_email,:create,:generate_code]
  before_filter :check_admin_right,:except=>[:new,:create,:edit,:change_password,:update_password,
    :update,:check_login,:check_email,:apply_agent,:update_agent_status_apply,:agent_edit,
    :update_agent_status_withdraw,:generate_code]
  # Be sure to include AuthenticationSystem in Application Controller instead
  
  def index
    @users = User.paginate :page => params[:page],:per_page =>20
  end

  # render new.rhtml
  def new
    @user = User.new()
  end

  def create
    if simple_captcha_valid?
      cookies.delete :auth_token
      # protects against session fixation attacks, wreaks havoc with
      # request forgery protection.
      # uncomment at your own risk
      # reset_session
      @user = User.new(params[:user])
      @user.save
      if @user.errors.empty?
        self.current_user = @user
        redirect_back_or_default('/')
        flash[:notice] = "欢迎加入TT!"
      else
        render :action => 'new'
      end
    else
      flash[:notice] = "验证码错误!"
      redirect_to :action => 'new'
    end
  end
  
  # render edit.rhtml
  def edit
    @user = User.find(params[:id])
  end

  def show
    @user = User.find(params[:id])
    render :layout=>false
  end

  def apply_agent
    @user = User.find(session[:user_id])
  end

  def update_agent_status_apply
    @user = current_user
    if @user.update_attributes(params[:user])
      redirect_to_tips("感谢您对TT小站的支持，您的申请已提交，管理员会在2个工作日内处理，审批结果会发到您的邮箱（#{@user.email}）")
    else
      render :action => 'apply_agent'
    end
  end

  def update_agent_status_pass
    @user = User.find(params[:id])
    if !@user.has_right?(AGENT_ROLE_CODE )
      role = Role.find(AGENT_ROLE_CODE)
      @user.roles << role
      @user.agent_status = AGENT_PASS_STATUS
      @user.discount = params[:user][:discount]
      @user.code = UUIDTools::UUID.random_create().to_s[0,6]
      if @user.save!
        flash[:notice] = "成功把该用户设置为代理商"
        redirect_to'/store/mine'
      else
        render :action => 'activation_agent'
      end
    else
      flash[:notice] = "该用户已经是代理商"
      redirect_to'/store/mine'
    end
  end

  def update_agent_status_withdraw
    @user = current_user
    @user.agent_status = AGENT_WITHDRAW_STATUS
    if @user.save!
      redirect_to_tips("感谢您对TT小站的支持，您的申请已提交，管理员会在5个工作日内处理您的提现申请，汇款后会以邮件方式通知您。、")
    else
      render :action => 'apply_agent'
    end
  end

  def change_password
    @user = User.find(params[:id])
  end

  def update_password
    @user = User.find(current_user)
    if User.authenticate(@user.login, params[:old_password])
      if @user.update_attributes(params[:user])
        flash[:notice] = "密码修改成功"
        redirect_to '/store/mine'
      else
        render :action => 'change_password'
      end
    else
      flash[:notice] = "旧密码不正确"
      render :action => 'change_password'
    end
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:notice] = "用户资料修改成功"
      redirect_to '/store/mine'
    else
      render :action => 'edit'
    end
  end

  def destroy
    @user = User.find(params[:id])
    @user.destroy

    respond_to do |format|
      format.html { redirect_to(users_url) }
      format.xml  { head :ok }
    end
  end

  def check_login
    result = User.find_by_login(params[:user][:login]) ? "false":"true"
    render :text=>   result
  end

  def check_email
    result = User.find_by_email(params[:user][:email]) ? "false":"true"
    render :text=>   result.to_s
  end

  def list_role
    @user=User.find(params[:id])
    @all_roles = Role.find(:all)
  end

  def update_role
    @user=User.find(params[:id])
    @user.roles.clear

    for item_hash in params[:role].values
      #chech_box没有选中的时候，提交的值为"0"
      if item_hash.values[0] !="0"
        role=Role.find(item_hash.values[0])
        @user.roles << role
      end
    end

    if @user.save
      flash[:notice] = '修改成功'
      redirect_to :action=>'index'
    end
  end

  def agent_list
    @agents = User.agent_list
    @applicants = User.find(:all,:conditions=>{:agent_status=>1})
    @withdraws = User.find(:all,:conditions=>{:agent_status=>2})
  end

  def activation_agent
    @user=User.find(params[:id])
  end

  def agent_edit
    @user = current_user
    @orders = Order.find_all_by_agent_id_and_status(session[:user_id],5)
  end

  def generate_code
    @domain = URI.encode(DOMAIN)
    @img_path  = Photo.find(params[:photo_id]).url_relative_path
    render :template=> "/users/generate_code.js.erb",:layout=>false
  end

end